import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import 'rxjs/add/operator/toPromise';
import {AddCompanyPage, AddCompany} from './company';
import {Router} from '@angular/router';
import {UserService} from '../user/user.service';

@Injectable()
export class CompanyService {
  public token: string;
  private hostUrl = ParamConfig.HTTP_WEB_HOST_URL + 'company/listCompany'; // 查询公司
  private hostUrlSaveCompany = ParamConfig.HTTP_WEB_HOST_URL + 'company/addCompany'; // 保存公司
  private hostUrlDeleteCompany = ParamConfig.HTTP_WEB_HOST_URL + 'company/deleteCompany'; // 删除公司
  private hostUrlUpdateCompany = ParamConfig.HTTP_WEB_HOST_URL + 'company/updateCompany'; // 修改公司
  constructor(private http: Http, private userService: UserService, private router: Router) {
  };

// 查询公司
  getCompany(page): Promise<any> {
    const request = JSON.stringify({
      rows: ParamConfig.DATA_LIST_PAGE_SIZE,
      page: page,
      criteria: {
        name: ''
      }
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrl, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            const pagedata = new AddCompanyPage();
            pagedata.addCompany = body as AddCompany[];
            pagedata.totalPages = body.total;
            return pagedata;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 增加
  addCompanyInfo(addCompany: AddCompany): Promise<any> {
      const request = JSON.stringify({
      name: addCompany.name,
      phone: addCompany.phone,
      contacts: addCompany.contacts,
      remark: addCompany.remark,
      address: addCompany.address,
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlSaveCompany, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

// 修改用户
  updateCompanyinfo(addCompany: AddCompany, companyId): Promise<any> {
    const request = JSON.stringify({
      companyId: companyId,
      name: addCompany.name,
      phone: addCompany.phone,
      contacts: addCompany.contacts,
      password: addCompany,
      address: addCompany.address,
      remark: addCompany.remark
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlUpdateCompany, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 删除公司
  removeUserinfo(addCompany: AddCompany): Promise<any> {
    const request = JSON.stringify({
      companyId: addCompany.companyId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlDeleteCompany, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
